import { materialProcess, getAllMaterials } from "../../dal/material/MaterialRepo";
import { PageRequest, PageResponse } from "../../dto/page";
import { validateEmptyWithName } from "../../util/validate";

/* 
获取随机指定数目药材
*/
export async function getRandomMaterials(num: number) {
    const outCome = await getAllMaterials(null)
    shuffleArray(outCome.items);
    var arr: any[] = outCome.items;
    return materialProcess(arr.slice(0, num))
}

/* 
分页获取药材
*/
export async function getPageMaterials(pageRequest: PageRequest) {
    validataPageParam(pageRequest)
    const result = await getAllMaterials(pageRequest.keyword);
    const fainlResult = materialProcess((await result).items.slice((pageRequest.page - 1) * pageRequest.size, pageRequest.page * pageRequest.size));
    const pageResponse: PageResponse = {
        current: pageRequest.page,
        records: fainlResult,
        size: fainlResult.length.toString()
    };
    return pageResponse;
}

/* 
打乱数组
*/
function shuffleArray(array: any[]) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }

}

/* 
参数校验
*/
function validataPageParam(page: PageRequest) {
    if(page.page===undefined||page.size===undefined)
        validateEmptyWithName([{name:"page",value:page.page},{name:"size",value:page.size}]);
}
